package cn.ts.today_school.controller;


import cn.ts.today_school.common.JsonResult;
import cn.ts.today_school.common.StatusCode;
import cn.ts.today_school.mapper.UserMapper;
import cn.ts.today_school.pojo.dto.UserRegDTO;
import cn.ts.today_school.pojo.entity.User;
import cn.ts.today_school.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.jws.WebMethod;
import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("v1/users/")
@Slf4j
@Api(tags = "用户模块")
@Validated
public class UserController {

    @Autowired(required = false)
    private UserMapper userMapper;

    @PostMapping("reg")
    @ApiOperation(value = "注册功能")
    public JsonResult reg(@RequestBody @Validated UserRegDTO userRegDTO, @ApiIgnore HttpSession session){
        String username = userRegDTO.getUsername();
        String email = userRegDTO.getEmail();
        UserVO byUsername = userMapper.findByUsername(username);
        UserVO byEmail = userMapper.findByEmail(email);
        if(byUsername == null){
            if(byEmail == null){
                User user = new User();
                BeanUtils.copyProperties(userRegDTO,user);
                session.setAttribute("user",userRegDTO);
                userMapper.addUser(user);
                return JsonResult.ok(userRegDTO);
            }
            return new JsonResult(StatusCode.EMAIL_ALREADY_EXISTS);
        }
        return new JsonResult(StatusCode.USERNAME_ALREADY_EXISTS);
    }
}
